//
//  RAMessage.m
//  ReplyAssistant
//
//  Created by liaozhenming on 2018/11/22.
//  Copyright © 2018 KK. All rights reserved.
//

#import "RAMessage.h"

#import "NSDate+Helper.h"
#import "RASender.h"


@implementation RAMessage

+ (instancetype)itemWithJson:(NSDictionary*)json {
    RAMessage *item = [RAMessage new];
    if ([json isKindOfClass: [NSDictionary class]]) {
        NSString *type = json[@"type"];
        NSDictionary *fr = json[@"fr"];
        RASender *sender = nil;
        if (fr) {
            sender = [RASender itemWithJson: fr];
        }
        
        NSString *content = json[@"content"];
        
        if ([type isEqualToString: @"text"]) {
            //  初始化文本消息
            item = [RATextMessage messageWithText: content sender: sender];
        }
        else {
            //  初始化图片消息
            item = [RAImageMessage messageWithImagePath: content sender: sender];
        }
        
        double timestamp = [json[@"timestamp"] doubleValue];
        item.timestamp = timestamp;
        item->_isSelf = [sender.identifier isEqualToString: KKUser.uid];
    }
    return item;
}

#pragma mark - getter methods

- (NSString*)sender {
    return _senderItem.identifier;
}

- (NSString*)senderHeadImg {
    return _senderItem.headimg;
}

- (NSDate*)timeDate {
    return [NSDate dateWithTimeIntervalSince1970: self.timestamp/1000];
}

- (NSDictionary*)parmeters {
    return @{};
}

- (NSString*)kk_showDescription {
    return @"";
}

@end


@implementation RAMessage(ShowAPIs)

- (CGSize)kk_contentSizeWithWidth:(CGFloat)width {
    return CGSizeMake(width, 0);
}

- (NSString*)kk_showTime {
    
    NSDate *messageTime = [NSDate dateWithTimeIntervalSince1970: self.timestamp];
    
    NSDate *now = [NSDate date];
    NSString *todayString = [now translateToStringWithFormat: @"HH:mm:ss"];
    NSArray *arr_todayTime = [todayString componentsSeparatedByString: @":"];
    NSTimeInterval spaceValue = 0.0;
    if (arr_todayTime.count == 3) {
        spaceValue = [arr_todayTime[0] doubleValue] * 3600 + [arr_todayTime[1] doubleValue] * 60 + [arr_todayTime[2] doubleValue];
    }
    NSTimeInterval offsetValue = [messageTime timeIntervalSinceNow];
    offsetValue -= spaceValue;
    NSString *dateString = @"";
    offsetValue = ABS(offsetValue);
    if (offsetValue < 3600.0 * 24 * 3) {
        if (offsetValue > 3600.0 * 48 && offsetValue < 3600.0 * 72) {
            dateString = @"前天";
        }
        else if (offsetValue > 3600.0 * 24 && offsetValue < 3600.0 * 48) {
            dateString = @"昨天";
        }
        else {
            dateString = [messageTime translateToStringWithFormat: @"HH:mm"];
        }
    }
    else {
        dateString = [messageTime translateToStringWithFormat: @"yyyy-MM-dd"];
    }
    return dateString;
}

@end


#pragma mark - RATextMessage Class
@implementation RATextMessage
//  初始化文本消息
+ (instancetype)messageWithText:(NSString*)text sender:(RASender*)sender {
    RATextMessage *item = [RATextMessage new];
    item.content = text;
    item.timestamp = [[NSDate date] timeIntervalSince1970] * 1000;
    item->_type = RAMessageType_Text;
    item->_senderItem = sender;
    item.isSelf = [sender.identifier isEqualToString: KKUser.uid];
    return item;
}

- (CGSize)kk_contentSizeWithWidth:(CGFloat)width {
    
    if (self.content == nil) {
        return CGSizeMake(width, 0);
    }
    
//    NSMutableParagraphStyle *paraStyle = [NSMutableParagraphStyle new];
//    paraStyle.lineBreakMode = NSLineBreakByCharWrapping;
//    paraStyle.alignment = NSTextAlignmentLeft;
//    paraStyle.lineSpacing = 8;
//    paraStyle.hyphenationFactor = 1.0;
//    paraStyle.firstLineHeadIndent = 0.0;
//    paraStyle.paragraphSpacingBefore = 0.0;
//    paraStyle.headIndent = 0;
//    paraStyle.tailIndent = 0;
    
//    NSDictionary *attributeDict = [NSDictionary dictionaryWithObjectsAndKeys: [UIFont systemFontOfSize: 15], NSFontAttributeName,[UIColor blackColor], NSForegroundColorAttributeName,paraStyle,NSParagraphStyleAttributeName,nil];
    
    NSDictionary *attributeDict = [NSDictionary dictionaryWithObjectsAndKeys: [UIFont systemFontOfSize: 15], NSFontAttributeName,[UIColor blackColor], NSForegroundColorAttributeName,nil];
    
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString: @""];
    NSAttributedString *string = [[NSAttributedString alloc]initWithString: self.content attributes: attributeDict];
    [attributedString appendAttributedString: string];
    CGRect contentRect=[attributedString boundingRectWithSize: CGSizeMake(width, MAXFLOAT) options: NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading context: nil];
    
    return contentRect.size;
}

- (NSDictionary*)parmeters {
    return @{@"type":@"text",@"content": self.content != nil ? self.content : @""};
}

- (NSString*)kk_showDescription {
    return self.content;
}

@end

#pragma mark - RAImageMessage Class
@implementation RAImageMessage

+ (CGSize)setImageShowSize:(CGSize)imageSize {
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat scale = height / width;
    if (width < 60) {
        width = 60;
        height = width *scale;
        height = MIN(height, 120);
    }
    else {
        width = MIN(120, width);
        height = width *scale;
        height = MIN(height, 240);
    }
    return CGSizeMake(width, height);
}

//  初始化图片消息
+ (instancetype)messageWithImagePath:(NSString*)path sender:(RASender*)sender {
    
    NSString *tmpPath = [NSString stringWithString: path];
    if (![path hasPrefix: @"http"]) {
        tmpPath = [NSString stringWithFormat: @"%@%@",APP_Request_BasicURLString,path];
    }
    
    RAImageMessage *item = [RAImageMessage new];
    item.imgPath = tmpPath;
    item.timestamp = [[NSDate date] timeIntervalSince1970] * 1000;
    item->_type = RAMessageType_Image;
    item->_senderItem = sender;
    item.isSelf = [sender.identifier isEqualToString: KKUser.uid];
    
    NSString *parmeters = [path lastPathComponent];
    if (parmeters != nil) {
        NSArray *tmp_resuluts = [parmeters componentsSeparatedByString: @"&"];
        NSString *widthString = [tmp_resuluts firstObject];
        NSString *heightString = [tmp_resuluts lastObject];
        NSArray *width_result = [widthString componentsSeparatedByString: @"="];
        NSArray *height_result = [heightString componentsSeparatedByString: @"="];
        
        CGFloat width = [width_result.lastObject floatValue];
        CGFloat height = [height_result.lastObject floatValue];
        
        item.imgSize = [self setImageShowSize: CGSizeMake(width, height)];
    }
    return item;
}

//  初始化图片消息
+ (instancetype)messageWithImage:(UIImage*)image sender:(RASender*)sender {
    
    RAImageMessage *item = [RAImageMessage new];
    item.image = image;
    item.imgSize = [self setImageShowSize: image.size];
    item.timestamp = [[NSDate date] timeIntervalSince1970] * 1000;
    item->_type = RAMessageType_Image;
    item->_senderItem = sender;
    item.isSelf = [sender.identifier isEqualToString: KKUser.uid];
    return item;
}

- (CGSize)kk_contentSizeWithWidth:(CGFloat)width {
    return CGSizeMake(self.imgSize.width, self.imgSize.height + 10);
}

- (NSDictionary*)parmeters {
    return @{@"type":@"image",@"content": self.imgPath != nil ? self.imgPath : @""};
}

- (NSString*)kk_showDescription {
    return @"[图片]";
}

@end
